<template>
    <div class="common-layout">
        <el-container>
            <el-main>
                <!-- 按钮组件 -->
                <div class="btn">
                    <div class="inp">
                        <el-input placeholder="请输入优惠劵名称" clearable v-model="datas.title" />
                    </div>
                    <div class="inp">
                        <el-select v-model="datas.type" clearable class="m-2" placeholder="请选择优惠劵类型">
                            <el-option v-for="item in couponType" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <div class="inp">
                        <el-select v-model="datas.status" clearable class="m-2" placeholder="请选择优惠劵状态">
                            <el-option v-for="item in couponState" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <el-button type="primary" :icon="Search" @click="init">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
                    <el-button type="primary" :icon="Download" @click="download">当前页导出</el-button>
                </div>
                <!-- 表格组件 -->
                <div id="tab">
                    <el-table :data="couponData" border width="100%">
                        <el-table-column prop="id" label="优惠劵ID" sortable align="center" width="120" />
                        <el-table-column prop="title" label="优惠劵名称" align="center" width="120" />
                        <el-table-column prop="type" label="优惠劵类型" align="center" width="120">
                            <template #default="scope">
                                {{ scope.row.type == 1 ? '满减劵' : '立减劵' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="description" label="介绍" align="center" width="120" />
                        <el-table-column prop="total" label="优惠劵数量" align="center" width="120" />
                        <el-table-column prop="surplus" label="剩余数量" align="center" width="120" />
                        <el-table-column prop="limit" label="每人限额" align="center" width="120" />
                        <el-table-column prop="discount" label="满减限额" align="center" width="120" />
                        <el-table-column prop="min" label="最低消费" align="center" width="120" />
                        <el-table-column label="状态" align="center" width="120">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == '1' ? 'primary' : 'danger'">
                                    {{ handlerProcessingStatus(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryTitle" label="使用类目名称" align="center" width="120">
                            <template #default="scope">
                                <el-tag>{{ scope.row.categoryTitle ? scope.row.categoryTitle : '全部类目' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryId" label="使用类目ID" align="center" width="120" />
                        <el-table-column prop="days" label="领劵相对天数" align="center" width="120">
                            <template #default="scope">
                                {{ scope.row.days ? scope.row.days : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtStart" label="领劵开始时间" align="center" width="120" />
                        <el-table-column prop="gmtEnd" label="领劵结束时间" align="center" width="120" />
                        <el-table-column label="操作时间" align="center" width="200" prop="status">
                            <template #default="scope">
                                <el-button @click="handleState(scope.row)"
                                    :type="scope.row.status == '1' ? 'danger' : 'primary'">
                                    {{ scope.row.status == '-1' ? '已过期' : scope.row.status == '1' ? '冻结' : '激活' }}
                                </el-button>
                                <el-button type="info" @click="handleLook(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页组件 -->
                <Pagination @page-change="handlePagehange" v-bind="datas" />
                <!-- 添加+编辑弹出框 -->
                <el-dialog v-model="dialogFormVisible" :title="bool ? '编辑' : '创建'" destroy-on-close>
                    <el-form ref="ruleFormRef" :model="form" :rules="rules" :disabled="bool == true"
                        label-width="120px">
                        <el-form-item label="优惠券名称" prop="title">
                            <el-input v-model="form.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="优惠券类型" prop="type">
                            <el-select v-model="form.type" clearable placeholder="请选择优惠券类型">
                                <el-option label="满减券" value="1" />
                                <el-option label="立减券" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="介绍" prop="description">
                            <el-input v-model="form.description" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="优惠券数量" prop="total">
                            <el-input v-model="form.total" autocomplete="off">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="每人限领" prop="limit">
                            <el-input v-model="form.limit" autocomplete="off">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠金额" prop="discount">
                            <el-input v-model="form.discount" autocomplete="off">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="最低消费" prop="min">
                            <el-input v-model="form.min" autocomplete="off">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠券状态" prop="status">
                            <el-select v-model="form.status" clearable placeholder="请选择优惠券状态">
                                <el-option label="正常" value="1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="有效期">
                            <el-radio-group v-model="expiration" @change="change">
                                <el-radio-button :label="0">领劵相对天数</el-radio-button>
                                <el-radio-button :label="1">指定绝对时间</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="expiration == 0">
                            <el-input v-model.number="form.days">
                                <template #append>天</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item v-else prop="gmtEnd">
                            <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="选择日期"
                                @change="getStartTime" />
                            至
                            <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="选择日期"
                                @change="getEndTime" />
                        </el-form-item>
                        <el-form-item label="商品限制范围">
                            <el-button-group class="button-group">
                                <el-button :type="booles ? 'primary' : ''" @click="booles = true">全场通用</el-button>
                                <el-button :type="booles ? '' : 'primary'" @click="booles = false">指定分类</el-button>
                            </el-button-group>
                        </el-form-item>
                        <el-form-item label="优惠类目" v-if="!booles">
                            <div class="m-4">
                                <el-cascader v-model="form.categoryId" :options="category" @change="changeOptins"
                                    :props="{ checkStrictly: true, label: 'title', value: 'id', children: 'childrenList' }" />
                            </div>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="bool == false">
                                确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import type { User, forms } from '@/type/params'//引入类型
import { ref, onMounted, reactive } from 'vue'//引入响应式，生命周期
import { Search, Plus, Download } from '@element-plus/icons-vue'//引入图标
import { post } from '@/untils/request'//引入请求方式
import Pagination from '@/components/Pagination.vue' //引入分页组件
import FileSaver from 'file-saver'//引入导出插件
import XLXS from "xlsx"//引入XLXS
import { couponDates } from '@/time/friendlTime'//引入友好日期
import { ElMessage } from 'element-plus'//引入消息提示框
import type { FormInstance } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)//显示/隐藏弹框
const couponData = ref([])//优惠劵列表
const datas = ref({//渲染页面数据
    total: 0,
    pageNo: 1,//当前页面
    limit: 10,//一页面所显示的条数
    _gp: 'admin.coupon',
    _mt: 'list',
    title: '',//搜索框关键词
    status: undefined,
    type: undefined
})
let expiration = ref(0)//标识,判断领劵相对天数与指定绝对时间
let bool = ref(false)//标识,判断进入添加/查看
let booles = ref(false)//标识,判断全场通用/指定分类

//弹框表单数据
let form = ref<forms>({
    title: '',
    total: 0,
    limit: 0,
    type: undefined,
    status: undefined,
    description: '',
    discount: 0,
    min: 0,
    categoryId: 0,
    days: "",
    gmtStart: "",
    gmtEnd: "",
    categoryTitle: ''
})
//清空后的表单
const clerrFroms = ref({
    ...form.value
})
const category = ref([])

const couponType = ref([
    {
        value: 1,
        label: '满减劵',
    },
    {
        value: 2,
        label: '立减劵',
    },
    {
        value: '',
        label: '全部',
    },
])
const couponState = ref([
    {
        value: 0,
        label: '下架',
    },
    {
        value: 1,
        label: '正常',
    },
    {
        value: -1,
        label: '已过期',
    },
    {
        value: '',
        label: '全部',
    },
])

//生命周期---挂载后
onMounted(() => {
    init()
})
//渲染
function init() {

    post(datas.value).then(res => {//渲染优惠券列表
        let { items } = res.data
        let { data } = res
        couponData.value = items//赋值
        datas.value.total = data.total//赋值总条数
        couponData.value.map((item: any) => {//映射显示优惠劵结束与开始时间
            if (item.gmtEnd < new Date().getTime()) {
                item.status = -1
            }
            item.gmtStart = item.gmtStart ? couponDates(item.gmtStart) : '无'
            item.gmtEnd = item.gmtEnd ? couponDates(item.gmtEnd) : '无'
            return item
        })
    }).catch(err => {
        console.log(err);
    })
    const categorys = reactive({
        _gp: 'admin.category',
        _mt: 'categoryTree',
    })
    post(categorys).then(res => {//渲染类目列表
        category.value = res.data
    }).catch(err => {
        console.log(err);

    })
};

//非空验证
const rules = reactive({
    title: [{ required: true, trigger: 'blur', message: "优惠劵名称不能为空" }],
    type: [{ required: true, trigger: 'change', message: "优惠劵类型不能为空" }],
    total: [{ required: true, trigger: 'change', message: "优惠劵数量不能为空" }, { required: true, trigger: 'change', pattern: /^\d{0,}$/, message: "优惠劵数量不能有小数点" }],
    limit: [{ required: true, trigger: 'change', message: "每人限领不能为空" }],
    discount: [{ required: true, trigger: 'change', message: "优惠金额不能为空" }],
    min: [{ required: true, trigger: 'change', message: "最低消费不能为空" }],
    status: [{ required: true, trigger: 'change', message: "优惠劵不能为空" }],
})

//查看
function handleLook(row: forms) {
    console.log(row, 111);
    bool.value = true //bool为true进入添加
    dialogFormVisible.value = true //显示弹出框
    Object.assign(form.value, row)
    if (row.type == 1) {
        form.value.type = '满减券'
    } else if (row.status == 0) {
        form.value.type = '立减劵'
    }
    if (row.status == 1) {
        form.value.status = '正常'
    } else if (row.status == 0) {
        form.value.status = '下架'
    } else if (row.status == -1) {
        form.value.status = '已过期'
    }
    if (row.categoryId) {
        booles.value = false
    } else {
        booles.value = true
    }
    if (row.days) {
        expiration.value = 0
    } else {
        expiration.value = 1
    }
}
//添加
function add() {
    bool.value = false//bool为false进入添加
    dialogFormVisible.value = true //显示弹出框
    Object.assign(form.value, clerrFroms.value)
}
//监听--选择领劵相对天数与指定绝对时间互不干扰,各赋值为空
function change() {
    form.value.days = "";
    form.value.gmtStart = "";
    form.value.gmtEnd = "";
}

//弹框确定按钮
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        //判断优惠劵使用时长
        if (expiration.value == 0) {
            if (form.value.days == undefined || form.value.days == 0) {
                ElMessage.error('请正确填写时长,不能为空或为0')
            }
        } else {
            if (form.value.gmtStart > form.value.gmtEnd) {
                ElMessage.error('结束时间不能晚于开始时间')
            }
        }
        //判断全场通用,类型设置为空
        if (form.value.type == 0) {
            form.value.categoryId = undefined
        }
        //判断优惠数量是否大于每人限额
        if (Number(form.value.total) < Number(form.value.limit)) {
            ElMessage.error('每人限额不能高于优惠数量')
            return
        }
        //判断优惠金额是否大于最低消费
        if (Number(form.value.discount) > Number(form.value.min)) {
            ElMessage.error('优惠金额不能高于最低消费')
            return
        }
        if (valid) {
            if (bool.value == false) {//bool为false请求添加的接口
                let adds = {
                    _gp: 'admin.coupon',
                    _mt: 'create',
                    ...form.value
                }
                post(adds).then(res => {
                    let { errno, errmsg } = res
                    if (200 == errno) {
                        ElMessage.success('添加成功')
                        dialogFormVisible.value = false//隐藏对话框
                        init()//刷新
                    } else {
                        ElMessage.error(errmsg)
                    }
                }).catch(err => {
                    console.log(err);
                    ElMessage.info('添加失败')
                })
            }
        } else {
            return false
        }
    })
}

//选择开始日期
function getStartTime(value: number) {
    form.value.gmtStart = new Date(value).getTime()
}
//选择结束日期
function getEndTime(value: number) {
    form.value.gmtEnd = new Date(value).getTime()
}
//数据处理类目列表--截取id
function changeOptins(value: any) {
    form.value.categoryId = value.splice(-1)[0]
}
//分页
function handlePagehange(s: { page: number, limit: number }) {
    datas.value.title = ''
    datas.value.type = undefined
    datas.value.status = undefined
    datas.value.pageNo = s.page
    datas.value.limit = s.limit
    init()
}
//状态改变--激活/点击/已过期
function handleState(row: User) {
    let states = {
        _gp: 'admin.coupon',
        _mt: 'updateCouponStatus',
        id: row.id,
        status: row.status == '1' ? 0 : 1
    }
    if ('-1' != row.status) {
        post(states).then(res => {
            let { errno } = res
            if (200 == errno) {
                console.log(res, '改变状态');
                ElMessage.success(row.status == '1' ? '激活成功' : '冻结成功')
                init()
            } else {

            }
        }).catch(err => {
            console.log(err);
        })
    } else {
        ElMessage.error('优惠劵已过期')
    }
}
//判断状态
function handlerProcessingStatus(status: number) {
    if (status == 0) {
        return '下架';
    } else if (status == 1) {
        return '正常';
    } else if (status < 0) {
        return '已过期';
    }
}
//导出
function download() {
    const filename = '导出表格.xlsx';
    // 导出表格加id,通过表格id获取要导出的表格数据
    const wb = XLXS.utils.table_to_book(document.getElementById("tab"))
    const wbout = XLXS.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
    });
    try {
        FileSaver.saveAs(
            new Blob([wbout], {
                type: 'application/octet-stream',
            }),
            filename
        );
    } catch (e) {
        console.log(e)
    }
    return wbout
}
</script>
<style lang="less" scoped>
.el-container {
    .btn {
        width: 100%;
        display: flex;

        .inp {
            width: 200px;
            margin-right: 15px;
        }
    }

    .btn,
    #tab {
        margin-bottom: 20px;
    }

}
</style>
